package com.chao.mybatisplus.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chao.mybatisplus.entity.Hero;
import com.chao.mybatisplus.service.HeroService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/hero")
public class HeroController {

    @Autowired
    private HeroService heroService;

    @PostMapping("/saveOrUpdate")
    public Boolean saveOrUpdate(@RequestBody Hero hero) {
        return heroService.saveOrUpdate(hero);
    }

    @GetMapping("/page")
    public Page<Hero> page(@RequestParam Integer currentPage, @RequestParam Integer pageSize,
                           @RequestParam String keyword) {
        pageSize = Math.min(pageSize, 100);
        LambdaQueryWrapper<Hero> queryWrapper = Wrappers.<Hero>lambdaQuery()
                .like(StringUtils.isNotBlank(keyword), Hero::getName, keyword)
                .or()
                .like(StringUtils.isNotBlank(keyword), Hero::getNickName, keyword)
                .orderByDesc(Hero::getPublishTime);
        return heroService.page(new Page<>(currentPage, pageSize), queryWrapper);
    }

    @PostMapping("/removeBatch")
    public Boolean removeBatch(@RequestBody List<String> heroIds) {
        return heroService.removeBatchByIds(heroIds);
    }
}
